package lazy2.tool.beangenerator.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import lazy2.util.StringUtil;

public class BGController {
	private BGView  view;
	private BGModel model;
	private boolean validateAll() {
		boolean res = false;
		if(StringUtil.isEmpty(view.getDBAddress())) {
			view.showErrorMessage("請填寫資料庫位址！");
		} else if(StringUtil.isEmpty(view.getDBName())) {
			view.showErrorMessage("請填寫資料表名稱！");
		} else if(StringUtil.isEmpty(view.getDBUser())) {
			view.showErrorMessage("請填寫登入帳號！");
		} else if(StringUtil.isEmpty(view.getDBPassword())) {
			view.showErrorMessage("請填寫登入密碼！");
		} else if(StringUtil.isEmpty(view.getOutputPath())) {
			view.showErrorMessage("請選擇輸出位置！");
		} else {
			res = true;
		}
		return res;
	}
	private String[] getTableNames() {
		if(StringUtil.hasText(view.getDBTables())) {
			String[] tables = view.getDBTables().split(",");
			for(int i=0,len=tables.length;i<len;i++) {
				tables[i] = tables[i].trim();
			}
			return tables;
		}
		return null;
	}
	private void init() {
		view.addGenerateBeanListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				SwingUtilities.invokeLater(new Runnable() {
					@Override
					public void run() {
						view.setGenButtonEnabled(false);
						new Thread(new Runnable() {
							@Override
							public void run() {
								if(validateAll()) {
									boolean success = false;
									try {
										String[] tables = getTableNames();
										model.generateBean(view.getBeanType(), view.getSelectedDBType(), view.getDBAddress(), view.getDBName(), null, view.getDBUser(), view.getDBPassword(), view.getOutputPath(), view.getPackageName(), tables);
										success = true;
									} catch (Exception e) {
										view.showErrorMessage(e.getMessage());
									}
									if(success) JOptionPane.showMessageDialog(view, "輸出成功！");
								}
								view.setGenButtonEnabled(true);
							}
						}).start();
					}
				});
			}
		});
	}
	
	public BGController(BGModel model, BGView view) {
		this.model = model;
		this.view = view;
		init();
	}

	public BGView getView() {
		return view;
	}

	public BGModel getModel() {
		return model;
	}

	public void setView(BGView view) {
		this.view = view;
	}

	public void setModel(BGModel model) {
		this.model = model;
	}
	
	
}
